﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using System.Configuration;
using BreadWebAPI.Models;

namespace BreadWebAPI.Controllers
{
    public class ContentController : ApiController
    {
        CloudStorageAccount storageAccount;
        CloudTable table;

        public ContentController()
        {
            // need to make this code execute only once
            storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            table = tableClient.GetTableReference("Content");

        }

        // GET api/Content, return today's comments
        public IEnumerable<ContentEntity> Get([FromUri]string BreadDate)
        {
            if (String.IsNullOrEmpty(BreadDate))
                return null;

            // PartitionKey looks like "2015-01-08"
            string filter = String.Format("(PartitionKey eq '{0}')", BreadDate);

            // Create the table query.
            TableQuery<ContentEntity> query = new TableQuery<ContentEntity>().Where(filter);
            try
            {
                IEnumerable<ContentEntity> result = table.ExecuteQuery(query);
                if (result != null && result.Any())
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
            return null;
        }

        public void Post([FromBody]CommentsEntity value)
        {
        }

        // PUT api/comments/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/comments/5
        public void Delete(int id)
        {
        }
    }
}
